function new_struct = defstruc(old_struct, field_name, default_value);

% DEFSTRUC - initialize structure with default values if needed
%
%    SNEW = DEFSTRUC(SOLD, FIELD, DEFAULT) insures that all fields
%    in the cell array FIELD are present in SOLD.  If not present,
%    these fields are added to SNEW and initialized with values in
%    the cell array DEFAULT.
%
%    If SOLD is a structure array and new fields are to be added,
%    the value of FIELD is set to equal the specified value in
%    DEFAULT for each member of the structure array.

% By:   S.C. Molitor (smolitor@bme.jhu.edu)
% Date: April 14, 2000

if (nargin ~= 3)
   return
elseif (~isempty(old_struct) & ~isstruct(old_struct))
   return
elseif (~iscell(field_name))
   return
elseif (~iscell(default_value))
   return
end

% determine number of fields
% check field names are strings

num_field = min(length(field_name), length(default_value));
for i = 1 : num_field
   if (~ischar(field_name{i}))
      return
   end
end

% make copy of structure for output
% check for field existence
% create field with default value if field doesn't exist

new_struct = old_struct;
for i = 1 : num_field
   if (~isfield(new_struct, field_name{i}))
      if (length(new_struct) > 1)
         for j = 1 : length(new_struct)
            new_struct = setfield(new_struct, {j}, field_name{i}, default_value{i});
         end
      else
         new_struct = setfield(new_struct, field_name{i}, default_value{i});
      end
   end
end
return
